<template>
  <div>
    <Navbar :appTitle="appTitle" :rname="isShowScan ? 'scan' : ''" @ClickRight="clickCode('','', true)"/>

    <overlayAk
     :isShowOverlay="isShowOverlay"
     :isShowLoading="isShowLoading"
     :errorCode="errorCode"
    />

    <div
      class="form-content wrap-apply"
      :style="{
        top: GLOBAL.currentEnvironment ? '0' : '',
        height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 100px)',
        paddingBottom: GLOBAL.currentEnvironment ? '120px' : '',
      }"
    >
      <van-cell-group class="formItemFlex">
        <p class="label FormTit"><span></span>盘点单编号</p>
        <div class="haveUnitBox">
          <van-field
            input-align="right"
            readonly
            v-model="buildForm.taskCode"
          />
        </div>
      </van-cell-group>
      <div class="bottomLine"></div>
      <van-cell-group  class="formItemFlex">
        <p class="label FormTit"><span></span>盘点范围</p>
        <div class="haveUnitBox">
          <van-field
            input-align="right"
            readonly
            v-model="buildForm.inventoryScopeText"
            @click="showInventoryModel(buildForm.inventoryScopeText)"
          />
        </div>
      </van-cell-group>
      <div class="bottomLine"></div>

      <div>
        <van-tabs v-model="active" :offset-top="158" color="#1890FF">
          <van-tab :title="`全部（${entryDetails.length}）`">
            <div class="list" >
              <div class="wrap" 
                v-for="(p, i) in entryDetails"
                :key="p.goodsKey" 
                v-show="entryDetails.length != 0"
              >
                <van-cell-group>
                  <p class="label otherText">
                    <span>盘点明细（{{ i + 1 }}）</span>
                    <span class="deleteStyle" @click="deleteGoods(i)">删除</span>
                  </p>
                  <div class="bottomLine"></div>
                  <div class="top">
                    <div class="title titleWidth">
                      {{ p.goodsCode	 }}| {{ p.goodsName }}| {{ p.goodsSpec }}
                    </div>
                  </div>
                  <div class="center">
                    <div>
                      <p>
                        <span class="key">包装规格：</span>
                        <span class="value">{{ p.packageSpec	}}</span>
                      </p>
                      <p>
                        <span class="key">产地：</span>
                        <span class="value">{{ p.address	}}</span>
                      </p>
                      <p>
                        <span class="key">单位：</span>
                        <span class="value">{{ p.unitIdText	}}</span>
                      </p>
                    </div>
                  </div>

                  <van-cell-group class="formItemFlex">
                    <p class="label required FormTit"><span></span>批号</p>
                    <div class="haveUnitBox">
                      <van-field
                        v-model="p.batchCode"
                        placeholder="请选择"
                        input-align="right"
                        readonly
                        @click="showBatchCode(p, i)"
                      >
                      <template #right-icon>
                        <div style="display: flex;">
                          <van-icon
                            @click="showBatchCode(p, i)"
                            size="20"
                            color="#999"
                            name="arrow"
                            style="margin-top: 2px"
                          />
                        </div>
                      </template>
                      </van-field>
                    </div>
                  </van-cell-group>
                  <div class="bottomLine"></div>
                  <van-cell-group class="formItemFlex">
                    <p class="label required FormTit"><span></span>盘点库位</p>
                    <div class="haveUnitBox">
                      <van-field
                        v-model="p.latticeFullname"
                        placeholder="请选择或扫码"
                        input-align="right"
                        readonly
                        @click="showLatticeNotification(p, i)"
                      >
                      <template #right-icon>
                        <div style="display: flex;">
                          <van-icon
                            @click="showLatticeNotification(p, i)"
                            size="20"
                            color="#999"
                            name="arrow"
                            style="margin-top: 2px"
                          />
                          <van-icon
                            @click.stop="clickCode(p, i, false)"
                            size="20"
                            color="#999"
                            name="scan"
                            style="margin-top: 2px"
                          />
                        </div>
                      </template>
                      </van-field>
                    </div>
                  </van-cell-group>
                  <div class="bottomLine"></div>
                  <van-cell-group class="formItemFlex">
                    <p class="label required FormTit"><span></span>盘点数</p>
                    <div class="haveUnitBox">
                      <van-field
                        v-model="p.goodsNum"
                        :disabled="!(p.goodsBatchId != '' && p.latticeId != '')"
                        type="number"
                        placeholder="请输入"
                        input-align="right"
                        @input="goodsNumChange(p, i)"
                        :formatter="(e) => needInNumChange(e)"
                      />
                    </div>
                  </van-cell-group>
                  <div class="bottomLine"></div>
                  <van-cell-group class="formItemFlex">
                    <p class="label FormTit"><span></span>盈亏数</p>
                    <div class="haveUnitBox">
                      <van-field
                        v-model="p.profitLossNum"
                        readonly
                        type="number"
                        placeholder="请输入"
                        input-align="right"
                      />
                    </div>
                  </van-cell-group>
                </van-cell-group>
              </div>
              <div class="addGoodScontain">
                <div class="addgoods" @click="addInventoryGoods">
                  <van-icon name="plus" size="16px" color="#1890ff" style="top: 2px" />
                  <a>物品</a>
                </div>
              </div>
            </div>
          </van-tab>
          <van-tab :title="`盘盈（${buildForm.surplusList.length}）`">
            <div class="detailList" v-if="buildForm.surplusList && buildForm.surplusList.length != 0">
              <div
                v-for="(item, index) in buildForm.surplusList"
                :key="index"
                class="wrap"
              >
                <div class="top">
                  <div class="icon"></div>
                  <div class="title">
                    {{ item.goodsCode || '-' }} | 
                    {{ item.goodsName || '-' }} |
                    {{ item.goodsSpec || '-' }}
                  </div>
                </div>
                <div class="center">
                  <div>
                    <p>
                      <span class="key">包装规格：</span>
                      <span class="value">{{ item.packageSpec  || '-' }}</span>
                    </p>
                    <p>
                      <span class="key">产地：</span>
                      <span class="value">{{ item.address || '-' }}</span>
                    </p>
                    <p>
                      <span class="key">盘点库位：</span>
                      <span class="value">{{ item.latticeName || '-' }}</span>
                    </p>
                    <p>
                      <span class="key">账面数/盘点数：</span>
                      <span class="value">{{ item.latticeNum }} / {{ item.goodsNum }}</span>
                    </p>
                    <p>
                      <span class="key">盈亏数：</span>
                      <span class="value">{{ item.profitLossNum }}</span>
                    </p>
                  </div>
                </div>
                <div class="label">
                  <span class="tag"> {{ item.produceDate  || '-' }} </span>
                  <span class="tag"> {{ item.batchCode  || '-' }} </span>
                </div>
              </div>
            </div>
            <van-empty v-else description="盘盈为空" />
          </van-tab>
          <van-tab :title="`盘亏（${buildForm.lossList.length}）`">
            <div class="detailList" v-if="buildForm.lossList && buildForm.lossList.length != 0">
              <div
                v-for="(item, index) in buildForm.lossList"
                :key="index"
                class="wrap"
              >
                <div class="top">
                  <div class="icon"></div>
                  <div class="title">
                    {{ item.goodsCode || '-' }} | 
                    {{ item.goodsName || '-' }} |
                    {{ item.goodsSpec || '-' }}
                  </div>
                </div>
                <div class="center">
                  <div>
                    <p>
                      <span class="key">包装规格：</span>
                      <span class="value">{{ item.packageSpec  || '-' }}</span>
                    </p>
                    <p>
                      <span class="key">产地：</span>
                      <span class="value">{{ item.address || '-' }}</span>
                    </p>
                    <p>
                      <span class="key">盘点库位：</span>
                      <span class="value">{{ item.latticeName || '-' }}</span>
                    </p>
                    <p>
                      <span class="key">账面数/盘点数：</span>
                      <span class="value">{{ item.latticeNum }} / {{ item.goodsNum }}</span>
                    </p>
                    <p>
                      <span class="key">盈亏数：</span>
                      <span class="value">{{ item.profitLossNum }}</span>
                    </p>
                  </div>
                </div>
                <div class="label">
                  <span> {{ item.produceDate  || '-' }} </span>
                  <span> {{ item.batchCode  || '-' }} </span>
                </div>
              </div>
            </div>
            <van-empty v-else description="盘亏为空" />
          </van-tab>
          <van-tab :title="`盘平（${buildForm.flatList.length}）`">
            <div class="detailList" v-if="buildForm.flatList && buildForm.flatList.length != 0">
              <div
                v-for="(item, index) in buildForm.flatList"
                :key="index"
                class="wrap"
              >
                <div class="top">
                  <div class="icon"></div>
                  <div class="title">
                    {{ item.goodsCode || '-' }} | 
                    {{ item.goodsName || '-' }} |
                    {{ item.goodsSpec || '-' }}
                  </div>
                </div>
                <div class="center">
                  <div>
                    <p>
                      <span class="key">包装规格：</span>
                      <span class="value">{{ item.packageSpec  || '-' }}</span>
                    </p>
                    <p>
                      <span class="key">产地：</span>
                      <span class="value">{{ item.address || '-' }}</span>
                    </p>
                    <p>
                      <span class="key">盘点库位：</span>
                      <span class="value">{{ item.latticeName || '-' }}</span>
                    </p>
                    <p>
                      <span class="key">账面数/盘点数：</span>
                      <span class="value">{{ item.latticeNum }} / {{ item.goodsNum }}</span>
                    </p>
                    <p>
                      <span class="key">盈亏数：</span>
                      <span class="value">{{ item.profitLossNum }}</span>
                    </p>
                  </div>
                </div>
                <div class="label">
                  <span> {{ item.produceDate  || '-' }} </span>
                  <span> {{ item.batchCode  || '-' }} </span>
                </div>
              </div>
            </div>
            <van-empty v-else description="盘平为空" />
          </van-tab>
        </van-tabs>
      </div>
      
      <div class="search-bottoms">
        <van-button class="btncancle" :loading="subLoading" loading-text="提交中..." @click="btnConfirm(false)">提交</van-button>
        <van-button class="btnconfirm" :loading="subLoading" loading-text="提交中..." @click="btnConfirm(true)">保存</van-button>
      </div>
    </div>
    <!--选择物品 -->
    <goods-pickers-ak
      v-if="showGoodsPicker"
      :listUrl="listUrl"
      :columns="goodsColumns"
      :selectedGoods="[]"
      @getCheckedGoods="getCheckedGoods"
    ></goods-pickers-ak>
    <!--选择批号 -->
    <batchCode-pickers-ak
      v-if="isShowbatchCode"
      :listUrl="batchCodeUrl"
      :columns="batchCodeColumns"
      :usedOutBox="false"
      :selectedGoods="[]"
      @handleList="handleBatchCodeList"
    ></batchCode-pickers-ak>
    <!--选择库位 -->
    <binLocation-pickers-ak
      v-if="isShowLatticeNotification"
      :listUrl="latticeNotificationUrl"
      :columns="latticeNotificationgColumns"
      :selectedGoods="[]"
      @handleList="handleList"
    ></binLocation-pickers-ak>
    <!-- 浏览器扫码组件 -->
    <qrcode
      :qrcode="codeForm.qrcode"
      :showClose="codeForm.showClose"
      v-show="codeForm.qrcode"
      :camera="camera"
      :torchActive="torchActive"
      @switchCamera="switchCamera"
      @ClickFlash="ClickFlash"
      @turnCameraOff="turnCameraOff"
      @onDecode="onDecode"
      @onInit="onInit"
    />
    <!-- 激光扫码组件 -->
    <PDAsao @changeScan="changeScan2" />
  </div>
</template>
<script>
import moment from "moment";
import Navbar from "@/components/navBar/navBar_right";
import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import GoodsPickersAk from "@/components/choiceuse/GoodsPickersAk";
import {
  itaskDetail,
  inventoryItask,
  getWarehouseLatticeDetail
} from "@/api/inventoryOrder";
import {
  getLatticeInfoForScan,
} from "@/api/removeAndinventory";
import store from "@/store";
import BinLocationPickersAk from "@/components/choiceuse/BinLocationPickersAk";
import batchCodePickersAk from "@/components/choiceuse/batchCodePickersAk";
import PDAsao from "@/components/scanCode/PDAsao.vue";
import { Dialog } from "vant";
import Decimal from 'decimal.js';
import overlayAk from "@/components/overlayAk";


export default {
  name: "inventoryItaskForm",
  components: {
    Navbar,
    VanFieldSelectPicker,
    GoodsPickersAk,
    BinLocationPickersAk,
    batchCodePickersAk,
    qrcode: () => import("@/components/scanCode"),
    PDAsao,
    overlayAk
  },
  data() {
    return {
      appTitle: "盘点",
      active: '',
      buildForm: {
        surplusList: [],
        lossList: [],
        flatList: [],
      },
      entryDetails:[],
      recentGoodsIndex: 0,
      subLoading: false,

      errorCode: 200,
      isShowOverlay: false,
      isShowLoading: false,
      
      showGoodsPicker: false,
      listUrl: "/baseSetting/wmsGoods/queryByPage",
      goodsColumns: {
        titleKey: ['goodsCode', 'goodsName', 'spec'], //标题
        content: [
          //内容
          {
            name: "产地",
            key: ["address"],
          },
          {
            name: "包装规格",
            key: ["packageSpec"],
          },
          {
            name: "单位",
            key: ["unitIdText"],
          },
        ],
        operationText: "",
      },

      isShowbatchCode: false,
      batchCodeUrl: "/wmsgoodsnotification/getBatchCode",
      batchCodeColumns: {
        titleKey: ["batchCode", "produceDate"], //标题
        content: [
          //内容
          {
            name: "所在库位",
            key: ["latticeInfo"],
          },
          {
            name: "库位库存",
            key: ["latticeNum"],
          },
          {
            name: "库存总数",
            key: ["goodsNum"],
          },
        ],
      },

      isShowLatticeNotification: false,
      latticeNotificationUrl: "/wmslattice/getLatticeNotificationInventory",
      latticeNotificationgColumns: {
        titleKey: ["latticeCode", "latticeName"], //标题
        content: [
          //内容
          {
            name: "排列层",
            key: ["locationInfo"],
          },
          {
            name: "库区名称",
            key: ["areaName"],
          },
          {
            name: "仓库名称",
            key: ["warehouseName"],
          },
        ],
        labelKey: [], //标签
        operationText: "",
      },

      isSave: true,
      // 扫码相关
      codeForm: {
        qrcode: false,
        showClose: false,
      },
      torchActive: true,
      camera: "off",
      isshow: false
    };
  },
  beforeRouteLeave(to, from, next) {
    if (this.showGoodsPicker || this.isShowbatchCode || this.isShowLatticeNotification) {
      this.showGoodsPicker = false;
      this.isShowbatchCode = false;
      this.isShowLatticeNotification = false;

      this.appTitle = '盘点';
      next(false);
    } else {
      next();
    }
  },
  async created() {
    store.commit("SET_CURRENT_PREFIX", "/jksaas-produce/produce");
    this.initData();
  },
  computed: {
    isShowScan() {
      if(this.showGoodsPicker || this.isShowbatchCode || this.isShowLatticeNotification || this.isShowOverlay){
        return false
      }else {
        return true
      }
    }
  },
  methods: {
    // 盘点范围详情 弹窗
    showInventoryModel(inventoryScopeText) {
      Dialog.confirm({
        title: '盘点范围',
        message: `${inventoryScopeText}`,
        showCancelButton: false,
        confirmButtonText: '我知道了',
        confirmButtonColor: '#4eabf0'
      }).then(() => {
      });
    },
    // 精准计算 盈亏数
    preciseSubtract(a, b) {
      if(a === '') {
        return 0;
      }
      return new Decimal(a).minus(b).toString();
    },
    // 盘点数change
    goodsNumChange(item, index) {
      try {
        if(!item.goodsBatchId || item.goodsBatchId =='') {
          throw new Error(`请选择批号`);
        }
        if(!item.latticeId || item.latticeId =='') {
          throw new Error(`请选择盘点库位`);
        }
      } catch(error) {
        this.$toast(error.message);
        return false;
      }

      this.recentGoodsIndex = index

      let {  goodsNum, latticeNum } = item

      this.entryDetails[this.recentGoodsIndex].profitLossNum = this.preciseSubtract(goodsNum, latticeNum)
      this.$forceUpdate()
    },
    // 初始化页面数据
    initData() {
      let id = this.$route.query.id;
      
      this.isShowOverlay = true
      this.isShowLoading = true

      if(id) { 
        // 盘点单详情 基本信息
        itaskDetail({id: id}).then((res) => {
          if (res.code == 200 && res.result) {
            this.buildForm = res.result;
            this.entryDetails = []
            this.getCheckedGoods(res.result.detailList)

            this.isShowOverlay = false
          } else {
            this.errorCode = res.code
            this.isShowLoading = false

            this.$toast(res.message);
          }

        }).catch((err) => {
          this.errorCode = 500
          this.isShowLoading = false
        })
      }
    },
    // 表单验证
    btnConfirm(isSave) {
      this.isSave = isSave

      try {
        // 入库物品明细 为空 选项名称、数量 表单验证
        if (this.entryDetails && this.entryDetails.length > 0) {
          this.entryDetails.forEach((element, index) => {
            if (!element.goodsBatchId) {
              throw new Error(`盘点明细（${index + 1}）批号不可为空`);
            }
            if (!element.latticeId) {
              throw new Error(`盘点明细（${index + 1}）盘点库位不可为空`);
            }
            if (!element.goodsNum) {
              throw new Error(`盘点明细（${index + 1}）盘点数不可为空`);
            }
          });
        } else {
          throw new Error(`请选择物品`);
        }
      } catch (error) {
        this.$toast(error.message);
        return false;
      }

      this.handleSubmit();
    },
    // 提交
    handleSubmit() {
      let params = {
        id: this.buildForm.id,
        type: this.isSave ? 'se' : 'ct', // se-保存，ct-提交
        detailList: this.entryDetails.map((ele) => {
          return {
            goodsBatchId: ele.goodsBatchId,
            latticeId: ele.latticeId,
            latticeNum: ele.latticeNum,
            goodsNum: ele.goodsNum,
          };
        }),
      };
      this.subLoading = true
      inventoryItask(params).then((res) => {
        if (res.success) {
          this.$toast(res.message);
          if(this.isSave) {
            this.initData()
          }else {
            this.$router.push({
              path: "/inventoryCheck/inventoryCheckOrder"
            });
          }
        } else {
          this.$toast(res.message);
        }
        this.subLoading = false
      }).catch(() => {
        this.subLoading = false
      }).finally(() => {
        this.subLoading = false
      })
    },

    // 确认选中批号 单选
    handleBatchCodeList(binLocationid, item, text) {
      this.isShowbatchCode = false;
      this.appTitle = '盘点';


      let { batchCode, goodsBatchId } = item
      let { id, latticeCode, latticeName, goodsNum } = item
      this.$set(this.entryDetails, this.recentGoodsIndex, { 
        ...this.entryDetails[this.recentGoodsIndex],
        batchCode: batchCode,
        goodsBatchId: goodsBatchId,

        latticeId: '',
        latticeCode: '',
        latticeName: '',
        latticeFullname: '',
        latticeNum: 0, // 账面数
        goodsNum: 0, // 盘点数
        profitLossNum: 0 // 盈亏数
      })
    },
    // 批号选择
    showBatchCode(item, index) {
      try {
        if(!item.goodsId || item.goodsId =='') {
          throw new Error(`物品数据异常`);
        }
      } catch(error) {
        this.$toast(error.message);
        return false;
      }

      this.batchCodeUrl = ""
      if(index != -1) {
        this.recentGoodsIndex = index
        this.batchCodeUrl = `/wmsgoodsnotification/getBatchCode?goodsId=${item.goodsId}` 
        this.appTitle = '批号';
        this.isShowbatchCode = true
      }
    },

    // 确认选中库位 单选
    handleList(binLocationid, item, text) {
      this.isShowLatticeNotification = false;
      this.appTitle = '盘点';
      let recGoods = this.entryDetails[this.recentGoodsIndex]

      try {
        this.entryDetails.forEach((ele) => {
          if(ele.goodsKey != recGoods.goodsKey) {
            if(ele.goodsId == recGoods.goodsId && ele.goodsBatchId == recGoods.goodsBatchId) {
              if(ele.latticeId == item.id) {
                throw new Error(`同个物品、同个批号下的盘点库位不能重复`);
              }
            }
          }
        })
      } catch(error) {
        this.$toast(error.message);
        return false;
      }

      let { id, latticeCode, latticeName, goodsNum } = item
      this.$set(this.entryDetails, this.recentGoodsIndex, { 
        ...this.entryDetails[this.recentGoodsIndex],
        latticeId: id,
        latticeCode: latticeCode,
        latticeName: latticeName,
        latticeFullname: latticeCode + '|' + latticeName,
        latticeNum: Number(goodsNum) || 0, // 账面数
        goodsNum: Number(goodsNum) || 0, // 盘点数
        profitLossNum: 0 // 盈亏数
      })
    },
    // 库位选择
    showLatticeNotification(item, index) {
      try {
        if(!item.goodsBatchId || item.goodsBatchId =='') {
          throw new Error(`请选择批号`);
        }
      } catch(error) {
        this.$toast(error.message);
        return false;
      }

      this.latticeNotificationUrl = ""
      if(index != -1) {
        this.recentGoodsIndex = index
        this.latticeNotificationUrl = `/wmslattice/getLatticeNotificationInventory?batchCode=${item.batchCode}&goodsId=${item.goodsId}&inventoryDimension=${this.buildForm.inventoryDimension}&inventoryScope=${this.buildForm.inventoryScope}` 
        this.appTitle = '库位';
        this.isShowLatticeNotification = true
      }
    },

    // 入库物品明细-》添加
    addInventoryGoods() {
      this.appTitle = "选择物品";
      this.showGoodsPicker = true;
    },
    // 入库物品明细-》删除
    deleteGoods(i) {
      this.entryDetails.splice(i, 1);
    },
    // 确认选中物品 物品可复选
    async getCheckedGoods(list) {
      this.showGoodsPicker = false;
      this.appTitle = '盘点';

      let checkedGoods = list.map((son) => {
        let { 
          detailId, goodsCode, goodsName, goodsId, id,
          goodsSpec, spec, unitIdText, packageSpec, address, batchCode, 
          latticeId, latticeName, latticeCode,goodsNum, latticeNum,
          goodsBatchId, profitLossNum
        } = son

        return {
          detailId: detailId || '',

          goodsKey: (goodsId || id) + '_' +   Math.floor(Math.random() * 1000), // 物品基本数据
          goodsId: (goodsId || id) || '',

          goodsCode: goodsCode || '',
          goodsName: goodsName || '',
          goodsSpec: (goodsSpec || spec) || '',

          packageSpec: packageSpec || '',
          address: address || '',
          unitIdText: unitIdText || '',

          batchCode: batchCode || '', // 批次数据
          goodsBatchId: goodsBatchId || '',

          latticeCode: latticeCode || '', // 库位数据
          latticeName: latticeName || '',
          latticeId: latticeId || '',
          latticeFullname: (latticeCode && latticeName) ? latticeCode + '|' + latticeName : '',

          goodsNum: goodsNum || '', // 盘点数 
          latticeNum: latticeNum || 0, // 账面数
          profitLossNum: profitLossNum || 0, // 盈亏数 --- 盈亏数=盘点数-账面数
        };
      });

      this.entryDetails = this.entryDetails.concat(checkedGoods)
    },

    // 盘点数  数量处理
    needInNumChange(e) {
      let value = this.clearNoNum(e);
      return value;
    },
    /*盘点数 处理*/
    clearNoNum(value, maxValue) {
      //先把非数字的都替换掉，除了数字和.
      value = value.replace(/[^\d.]/g, "");
      //保证只有出现一个.而没有多个.
      value = value.replace(/\.{2,}/g, ".");
      //必须保证第一个为数字而不是.
      value = value.replace(/^\./g, "");
      //保证.只出现一次，而不能出现两次以上
      value = value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      //只能输入四个小数
      value = value.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, "$1$2.$3");
      // console.log(value.includes('.'),'wwwwww')
      //小数位处理
      if (value.substring(0, 1) == "0" && value.substring(0, 2) != "0.") {
        value = '0';
      }
      //输入长度控制
      if (value > 9999999999.9999) {
        value = null;
      }

      return value;
    },

    // 扫码相关
    // 打开相机
    clickCode(item, index, isshow) {
      if(!this.isShowScan) {
        return false
      }
      if(!isshow) {
        try {
          if(!item.goodsBatchId || item.goodsBatchId =='') {
            throw new Error(`请选择批号`);
          }
        } catch(error) {
          this.$toast(error.message);
          return false;
        }
      }

      let that = this;
      this.recentGoodsIndex = index
      this.isshow = isshow

      let platform = localStorage.getItem("currentEnvironment");
      switch (platform) {
        case "iwork":
          var opt = {
            success: function(res) {
              console.log(JSON.stringify(res), "APP扫码数据");
              if (res.retCode == 0) {
                that.onDecode(res.retData);
              } else {
                that.$toast(res.retMsg);
              }
            },
            fail: function(err) {
              that.$toast("扫码失败！");
            },
          };
          //插件调用代码
          WorkHelper.scan(opt);
          break;
        case "browser":
          // camera:: 'front'--前摄像头，'rear'后摄像头，'off'关闭摄像头，会获取最后一帧显示，'auto'开始获取摄像头
          that.codeForm.qrcode = true;
          that.camera = "rear";
          break;
        case "dingding":
          dd.biz.util.scan({
            type: "qrCode", // type 为 all、qrCode、barCode，默认是all。
            onSuccess: function(data) {
              //onSuccess将在扫码成功之后回调
              that.onDecode(data.text);
            },
            onFail: function(err) {
              // console.error(err,'error')
            },
          });
          break;
        default:
          "";
          break;
      }
    },
    // 扫码结果回调
    onDecode(result) {
      // result, 扫描结果，可以根据自己的需求来实现相应的功能
      this.codeForm.code = JSON.parse(result);
      if (this.codeForm.code.EntityType == "lattice" && this.codeForm.code.id) {
        if(this.isshow) { // 扫库位码 获取库位关联物品
          let params = {
            id: this.codeForm.code.id, 
            scope: 'Inventory_sheet', 
            inventoryDimension: this.buildForm.inventoryDimension,
            inventoryScope: this.buildForm.inventoryScope
          }
          
          getLatticeInfoForScan(params).then((res) => {
            if(res.code == 200 && res.result) {
              if(res.result.length ==0) {
                this.$toast("该库位关联物品为空");
                this.clickCode('', this.recentGoodsIndex, true);
                return
              }

              let newGoodsList = res.result.map((son) => {
                let { 
                  goodsCode, goodsName, goodsId, spec, unitName, packageSpec, address,goodsNum,
                  batchCode, goodsBatchId,
                  latticeId, latticeName, latticeCode,
                } = son

                return {
                  detailId: '',

                  goodsKey: goodsId  + '_' +   Math.floor(Math.random() * 1000), // 物品基本数据
                  goodsId: goodsId || '',

                  goodsCode: goodsCode || '',
                  goodsName: goodsName || '',
                  goodsSpec: spec || '',

                  packageSpec: packageSpec || '',
                  address: address || '',
                  unitIdText: unitName || '',

                  batchCode: batchCode || '', // 批次数据
                  goodsBatchId: goodsBatchId || '',

                  latticeCode: latticeCode || '', // 库位数据
                  latticeName: latticeName || '',
                  latticeId: latticeId || '',
                  latticeFullname: (latticeCode && latticeName) ? latticeCode + '|' + latticeName : '',

                  latticeNum: goodsNum || 0, // 账面数
                  goodsNum: goodsNum || 0, // 盘点数 
                  profitLossNum: 0, // 盈亏数 --- 盈亏数=盘点数-账面数
                };
              });

              if(this.entryDetails.length != 0) {
                let array1Copy = this.mergeWithoutDuplicatesPreservingOriginals(this.entryDetails, newGoodsList);
                if(array1Copy.length != 0) {
                  this.entryDetails = this.entryDetails.concat(array1Copy) 
                }else {
                  this.$toast("物品、批号、盘点库位已存在");
                }
              }else {
                this.entryDetails = newGoodsList
              }

              this.turnCameraOff()
              this.isshow = false              
            }else {
              this.$toast(res.message);
            }
          })
        } else { // 扫库位码 获取库位
          getWarehouseLatticeDetail(this.codeForm.code.id).then((res) => {
            if(res.code == 200 && res.result) {
              if(res.result.status == 'effective') {
                let recLat = res.result
                let recGoods = this.entryDetails[this.recentGoodsIndex]

                try {
                  this.entryDetails.forEach((ele) => {
                    if(ele.goodsKey != recGoods.goodsKey) {
                      if(ele.goodsId == recGoods.goodsId && ele.goodsBatchId == recGoods.goodsBatchId) {
                        if(ele.latticeId == recLat.id) {
                          throw new Error(`同个物品、同个批号下的盘点库位不能重复`);
                        }
                      }
                    }
                  })
                } catch(error) {
                  this.$toast(error.message);
                  return false;
                }

                let { id, latticeCode, latticeName, goodsNum } = recLat
                this.$set(this.entryDetails, this.recentGoodsIndex, { 
                  ...this.entryDetails[this.recentGoodsIndex],
                  latticeId: id,
                  latticeCode: latticeCode,
                  latticeName: latticeName,
                  latticeFullname: latticeCode + '|' + latticeName,
                  latticeNum: Number(goodsNum) || 0, // 账面数
                  goodsNum: Number(goodsNum) || 0, // 盘点数
                  profitLossNum: 0 // 盈亏数
                })
                this.turnCameraOff()
              }else {
                this.$toast("该库位已被禁用");
                this.clickCode(recGoods, this.recentGoodsIndex, false);
              }
            }else {
              this.$toast(res.message);
            }
          })
        }

      } else {
        this.$toast("请扫正确二维码");
        if(this.isshow) {
          this.clickCode('', '', true);
        }else {
          this.clickCode(this.entryDetails[this.recentGoodsIndex], this.recentGoodsIndex, false);
        }
      }
    },
    // 相机反转
    switchCamera() {
      switch (this.camera) {
        case "front":
          this.camera = "rear";
          break;
        case "rear":
          this.camera = "front";
          break;
        default:
          this.$toast("错误");
      }
    },
    // 关闭相机
    turnCameraOff() {
      this.camera = "off";
      this.codeForm.qrcode = false;
    },
    // 打开手电筒
    ClickFlash() {
      switch (this.torchActive) {
        case true:
          this.torchActive = false;
          break;
        case false:
          this.torchActive = true;
          break;
        default:
          this.$toast("错误");
      }
    },
    // 检查是否调用摄像头
    async onInit(promise) {
      try {
        await promise;
      } catch (error) {
        if (error.name === "StreamApiNotSupportedError") {
        } else if (error.name === "NotAllowedError") {
          this.errorMessage = "Hey! I need access to your camera";
        } else if (error.name === "NotFoundError") {
          this.errorMessage = "Do you even have a camera on your device?";
        } else if (error.name === "NotSupportedError") {
          this.errorMessage =
            "Seems like this page is served in non-secure context (HTTPS, localhost or file://)";
        } else if (error.name === "NotReadableError") {
          this.errorMessage =
            "Couldn't access your camera. Is it already in use?";
        } else if (error.name === "OverconstrainedError") {
          this.errorMessage =
            "Constraints don't match any installed camera. Did you asked for the front camera although there is none?";
        } else {
          this.errorMessage = "UNKNOWN ERROR: " + error.message;
        }
      }
    },
    // 激光扫码
    changeScan2(v) {
      if (v.EntityType == "goods") {
        let params = {
          id: v.id, 
          scope: 'Inventory_sheet', 
          inventoryDimension: this.buildForm.inventoryDimension,
          inventoryScope: this.buildForm.inventoryScope
        }
        
        getLatticeInfoForScan(params).then((res) => {
          if(res.code == 200 && res.result) {
            if(res.result.length ==0) {
              this.$toast("该库位关联物品为空");
              return
            }

            let newGoodsList = res.result.map((son) => {
              let { 
                goodsCode, goodsName, goodsId, spec, unitName, packageSpec, address,goodsNum,
                batchCode, goodsBatchId,
                latticeId, latticeName, latticeCode,
              } = son

              return {
                detailId: '',

                goodsKey: goodsId  + '_' +   Math.floor(Math.random() * 1000), // 物品基本数据
                goodsId: goodsId || '',

                goodsCode: goodsCode || '',
                goodsName: goodsName || '',
                goodsSpec: spec || '',

                packageSpec: packageSpec || '',
                address: address || '',
                unitIdText: unitName || '',

                batchCode: batchCode || '', // 批次数据
                goodsBatchId: goodsBatchId || '',

                latticeCode: latticeCode || '', // 库位数据
                latticeName: latticeName || '',
                latticeId: latticeId || '',
                latticeFullname: (latticeCode && latticeName) ? latticeCode + '|' + latticeName : '',

                latticeNum: goodsNum || 0, // 账面数
                goodsNum: goodsNum || 0, // 盘点数 
                profitLossNum: 0, // 盈亏数 --- 盈亏数=盘点数-账面数
              };
            });

            if(this.entryDetails.length != 0) {
              let array1Copy = this.mergeWithoutDuplicatesPreservingOriginals(this.entryDetails, newGoodsList);
              if(array1Copy.length != 0) {
                this.entryDetails = this.entryDetails.concat(array1Copy) 
              }else {
                this.$toast("物品、批号、盘点库位已存在");
              }
            }else {
              this.entryDetails = newGoodsList
            }          
          }else {
            this.$toast(res.message);
          }
        })
      }
    },
    // 扫库位码 获取库位物品 数据处理
    mergeWithoutDuplicatesPreservingOriginals(arr1, arr2) {
      // 输入校验
      if (!Array.isArray(arr1) || !Array.isArray(arr2)) {
        throw new Error('输入必须为数组');
      }
      
      // 创建一个哈希表用于存储arr1中元素的索引
      const arr1IndexMap = new Map();
      arr1.forEach((item, index) => {
        if (!arr1IndexMap.has(item.goodsId)) {
          arr1IndexMap.set(item.goodsId, index);
        }
      });

      // 创建arr1的一个浅拷贝
      const newArray = [...arr1];
      let newList = [];

      // 遍历arr2
      arr2.forEach((item) => {
        const arr1Index = arr1IndexMap.get(item.goodsId);

        // 如果arr2中的元素在arr1中不存在，则加入到新列表中
        if (arr1Index === undefined) {
          newList.push(item);
        } else {
          // 比较arr1和arr2中相同goodsId的元素的其他属性
          const arr1Item = newArray[arr1Index];
          if (
            arr1Item.goodsBatchId !== item.goodsBatchId ||
            arr1Item.latticeId !== item.latticeId
          ) {
            newList.push(item);
          }
        }
      });
      // 将arr1中未在arr2中出现的元素加入到新列表中
      newArray.forEach((item) => {
        if (!arr1IndexMap.has(item.goodsId)) {
          newList.push(item);
        }
      });

      return newList;
    }
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
@import "@/views/workManagement/materialRequisition/materialForm.scss";
.tabs-contain {
  position: relative;

  /deep/.van-tabs__nav--line.van-tabs__nav--complete {
    width: calc(100% - 120px);
  }
  /deep/.van-tabs__wrap--scrollable .van-tab {
    width: 33%;
    min-width: 230px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .all-down-btn {
    position: absolute;
    top: 0;
    right: 0;
    width: 120px;
    height: 90px;
    font-size: 28px;
    color: rgb(25, 137, 250);
    line-height: 90px;
    text-align: center;
    background-color: #fff;
    /deep/.van-icon {
      top: 6px;
    }
  }
  .all-down-model {
    position: absolute;
    top: 0;
    right: 0;
    width: 100vw;
    background-color: #fff;
    z-index: 9;
    border-bottom: 1px solid #f3f3f3;
    padding: 6px;
    .tags-contain {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 10px;
      .goodsNameTag {
        width: 22%;
        margin: 10px 10px;
        padding: 5px 20px;
        background-color: #f3f3f3;
        color: #333333;
        border-radius: 5px;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        text-align: center;
        height: 60px;
        line-height: 42px;
      }
    }
    .ctrBtn-contian {
      height: 50px;
      text-align: center;
      color: #1890ff;
      font-size: 24px;
      line-height: 50px;
      /deep/.van-icon {
        top: 6px;
      }
    }
  }
}
.qrcodeModel{
  .nav_contain {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #ceced1;
    padding: 24px 20px 10px;
    span {
      font-size: 32px;
    }
    .left {
      color: #3ba1ff;
    }
    .center {
      color: #191f25;
      font-weight: bolder;
    }
    .right {
      color: #3ba1ff;
    }
  }
  .list {
    .wrap {
      background: #fff;
      width: 100vw;
      .otherText {
        display: flex; 
        justify-content: space-between;
        font-size: 32px;
        color: #191f25;
        margin: 0;
        font-weight: 500;
        .deleteStyle {
          font-weight: 400; 
          color: #ff4d4f
        }
      }
      .top {
        display: flex;
        justify-content: flex-start;
        padding-top: 10px;
        .icon {
          width: 6px;
          height: 32px;
          background: #1890ff;
          margin: 6px 10px 0 10px;
        }
        .title {
          width: 602px;
          margin-right: 20px;
          font-size: 30px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #191f25;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .titleWidth {
          width: 600px;
          margin: 0 25px;
        }
      }
      .center {
        margin: 0 0 30px;
        p {
          margin: 6px 25px;
          font-size: 28px;
          display: flex;
          position: relative;
          .key {
            color: #888888;
          }
          .value {
            color: #191f25;
            width: 380px;
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .arrow {
            color: #1890ff;
            position: absolute;
            right: -10px;
          }
          /deep/.van-tag {
            margin-right: 10px;
            width: 160px;
            flex-direction: column;
          }
        }
      }
    }
  }
}

.form-content {
  width: 100%;
  height: calc(100vh - 203px);
  background: #f5f5f5;
  padding: 20px 0 0;
  .formgroup {
    background: #ffffff;
    margin-top: 0.1rem;
    margin-bottom: 0.2rem;
    padding-top: 0.1rem;

    .title {
      width: 0.58rem;
      height: 0.14rem;
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
      line-height: 0.05rem;
      margin-left: 0.16rem;
    }
  }
  .search-bottoms {
    width: 100%;
    height: 100px;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: 0px;
    padding: 0rem 11px;
    box-sizing: border-box;
    font-size: 32px;
    font-weight: 500;
    z-index: 9;
    .btnconfirm {
      flex: 1;
      background: #1890ff;
      box-sizing: border-box;
      height: 78px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 6px;
      color: #ffffff;
    }
    .btncancle {
      width: 270px;
      margin: 0 30px;
      background: #f2f2f6;
      color: #1a2026;
      box-sizing: border-box;
      height: 78px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 6px;
    }
  }
}
.bottomLine {
  height: 1px;
  background-color: #f2f2f2;
  margin: 0 2px;
}
.haveUnitBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding-right: 32px;
  /deep/ .van-cell {
    padding-right: 0;
    width: 600px;
  }
  /deep/ .van-field__control {
    max-width: 700px;
  }
}
/deep/ .van-nav-bar {
  z-index: 99;
}
/deep/.van-sidebar-item--select::before {
  color: #1890ff;
  background-color: #1890ff;
}
/deep/.van-tree-select__item--active {
  color: #1890ff;
}
.addGoodScontain {
  display: flex;
  flex-wrap: nowrap;
  .addgoods {
    flex: 1;
    background: #fff;
    font-size: 32px;
    text-align: center;
    height: 78px;
    line-height: 78px;
    color: #1890ff;
  }
}
.required span::after {
  left: -20px;
  top: 3px;
}
.filedClear {
  width: 28px;
  height: 28px;
}
.formItemFlex {
  display: flex;
  flex-direction: row;
  .FormTit {
    flex: 1;
    min-width: 3.3rem;
    padding-top: 0.33rem;
  }
  .haveUnitBox {
    flex: 1;
    .van-cell {
      width: 6.2rem;
    }
  }
}
.list {
  height: 64vh;
  overflow: scroll;
  padding: 10px 0;
  .wrap {
    background: #fff;
    width: 100vw;
    margin: 5px 0 20px;
    .otherText {
      display: flex; 
      justify-content: space-between;
      font-size: 32px;
      font-weight: bold;
      color: #191f25;
      .deleteStyle {
        font-weight: 400; 
        color: #ff4d4f
      }
    }
    .top {
      display: flex;
      justify-content: flex-start;
      padding-top: 10px;
      .icon {
        width: 6px;
        height: 32px;
        background: #1890ff;
        margin: 6px 10px 0 10px;
      }
      .title {
        width: 602px;
        margin-right: 20px;
        font-size: 30px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #191f25;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .titleWidth {
        width: 600px;
        margin: 16px 25px;
      }
    }
    .center {
      p {
        margin: 16px 25px;
        font-size: 28px;
        display: flex;
        position: relative;
        .key {
          color: #888888;
        }
        .value {
          color: #191f25;
          width: 380px;
          display: block;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .arrow {
          color: #1890ff;
          position: absolute;
          right: -10px;
        }
      }
      .showAll {
        background: #f5f8ff;
        width: 100vw;
        margin-left: -30px;
        padding: 30px;
        margin-bottom: 30px;
      }
      .showAll2 {
        width: 100%;
        margin: 0 0 30px 0;
        padding: 30px 0;
      }
    }
    .label {
      margin-left: -0.03rem;
      margin-top: -0.1rem;
      .tag {
        height: 0.16rem;
        background: #f0f6fe;
        color: #1890ff;
        margin-right: 0.1rem;
        padding: 0.03rem 0.08rem;
        font-size: 24px;
        border-radius: 0.03rem;
      }
    }
  }
}
.detailList {
  height: 64vh;
  overflow: scroll;
  .wrap {
    background: #fff;
    margin: 10px 0;
    padding: 30px;
    width: 100vw;
    .top {
      display: flex;
      justify-content: flex-start;
      .icon {
        width: 6px;
        height: 36px;
        background: #1890ff;
        margin-top: 6px;
        margin-right: 20px;
      }
      .title {
        width: 620px;
        margin-right: 20px;
        font-size: 32px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #191f25;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        display: flex;
        justify-content: space-between;
      }
      .spot img {
        width: 40px;
        height: 40px;
      }
    }
    .center {
      p {
        margin: 16px 25px;
        font-size: 28px;
        display: flex;
        position: relative;
        .key {
          color: #888888;
        }
        .value {
          color: #191f25;
          width: 380px;
          display: block;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .arrow {
          color: #1890ff;
          position: absolute;
          right: -10px
        }      
        .fontAno {
          font-size: 30px;
          padding-left: 20px;
        }
      }
      .showAll {
        background: #f5f8ff;
        width: 100vw;
        margin-left: -0.15rem;
        padding: 0.15rem;
        margin-bottom: 0.15rem;
      }
    }
    .label {
      margin-left: -0.03rem;
      margin-top: -0.1rem;
      span {
        height: 0.16rem;
        background: #f0f6fe;
        color: #1890ff;
        margin-right: 0.1rem;
        padding: 0.03rem 0.08rem;
        font-size: 24px;
        border-radius: 0.03rem;
      }
    }
    .foot {
      display: flex;
      justify-content: space-between;
      font-size: 0.14rem;
      .pictures {
        width: 0.33rem;
        height: 0.33rem;
        line-height: 0.33rem;
        text-align: center;
        color: #fff;
        background: #1890ff;
        display: block;
        border-radius: 0.06rem;
        font-size: 0.12rem;
        margin-right: 0.1rem;
      }
      .text {
        width: 1rem;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .opera {
        color: #1890ff;
        font-size: 0.14rem;
      }
    }
  }
}
/deep/.van-field__control {
  text-overflow: ellipsis;
}
</style>
